package com.mes.invented.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.mes.invented.doman.VPart;
import com.mes.task.dao.TaskDao;

@Repository
public class VPartDao {
	@Resource
	TaskDao taskDao;
	
	/**
	 * 获取架次计划图号下拉框查询的值
	 * @author cswen
	 * @param typeParameter
	 * @param drawingid
	 * @param part_name
	 * @return
	 */
	public List<VPart> getVPartList(String typeParameter, String drawingid, String part_name) {
		List<VPart> vpartList = new ArrayList<>();
		String typeCondition = "";
		if (typeParameter != null && !typeParameter.equals("")) {
			String[] types = StringUtils.split(typeParameter, ',');
			typeCondition = Stream.of(types).map(s -> "'" + s + "'")
								  .collect(Collectors.joining(",", " and b.part_number_type in (", ")")); 
		}
		String sql = "select b.drawingid,"
				+ " b.versionid,"
				+ " b.part_name,"
				+ " b.part_sort2,"
				+ " r.routing,"
				+ " r.versionid,"
				+ " r.mastershop,"
				+ " md.deptname"
				+ " from bv_part b"
				+ " left join b_routine_header r on b.part_number = r.part_number"
				+ " left join r_dept md on r.mastershop = md.deptid"
				+ " where upper(b.drawingid) like replace(upper('" + drawingid + "'),'*','%')"
				+ " and upper(b.part_name) like replace(upper('" + part_name + "'),'*','%')"
				+ " and r.parentrouting is null"
				+ typeCondition + " order by b.drawingid";
		
		Session session = taskDao.getSessionFactory().getCurrentSession();
		List list = session.createSQLQuery(sql).list();
		translate(list, vpartList);
		return vpartList;
	}
	
	private void translate(List list, List<VPart> vpartList) {
		for(int i = 0; i < list.size(); i++){
			//获取当前记录
			Object[] tempOne = (Object[]) list.get(i);
			//中间复制实体
			VPart vPart = new VPart();
			//赋值到对应实体
			//需要提前判断非空不然toString()方法会报错
			if(tempOne[0]!=null){
				vPart.setDrawingId(tempOne[0].toString());
			}
			
			if(tempOne[1]!=null){
				vPart.setVersionId(tempOne[1].toString()); 
			}
			
			if(tempOne[2]!=null){
				vPart.setPartName(tempOne[2].toString());
			}
			
			if(tempOne[3]!=null){
				vPart.setModel(tempOne[3].toString());
			}
			
			if(tempOne[4]!=null){
				vPart.setRoutingId(tempOne[4].toString());
			}

			if(tempOne[5]!=null){
				vPart.setRouting_versionId(tempOne[5].toString());
			}
			
			if(tempOne[6]!=null){
				vPart.setMastershopId(tempOne[6].toString());
			}
			
			if(tempOne[7]!=null){
				vPart.setMastershopName(tempOne[7].toString());
			}
			
			vpartList.add(vPart);
		}
	}
}

















